package com.nord.EventList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.nord.R;
import com.nord.Menus.Menus;
import com.nord.Registration.Registration;
import com.nord.Services.SQLiteAdapter;
import com.nord.WebTools.HtmlBrowser;

public class EventList extends Activity {

	/*
	 * Data invariant: + eventList is a list of HashMaps - Hashmaps include
	 * event name,event expiry, event countdown, + listView is the ListView
	 * actvitiy widget
	 */
	private static List<HashMap<String, String>> eventList;
	private static HashMap<String, String> locationList;
	ListView listView;

	@Override
	public void onResume() {
	
		super.onResume();
		setContentView(R.layout.activity_event_list);

		listView = (ListView) findViewById(R.id.listView);
		Button tripBanner = (Button) findViewById(R.id.tripBanner);
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"DaysOne-Regular.ttf");
		tripBanner.setTypeface(tf);
		new EventExtractor().execute();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent selection = new Intent(EventList.this,Registration.class);
				selection.putExtra("EVENTNAME",	eventList.get(position).get("title"));
				selection.putExtra("USERNAME", getIntent().getExtras().getString("USERNAME"));
				selection.putExtra("LOCATION", locationList.get(eventList.get(position).get("title")));
				startActivity(selection);
			}
		});
	}

	private class EventExtractor extends AsyncTask<Void, Integer, String> {
		ProgressDialog progressBar;
		SimpleAdapter adapter;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(EventList.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að sækja nýjustu atburði frá www.nord.is/ ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			String[] htmlInfo = HtmlBrowser.getExecutor("http://www.nord.is/api/nord/events/?format=json&limit=10");
			String jsonString = htmlInfo[0];

			if(!htmlInfo[0].contains("Exception")){
				if(HtmlBrowser.cookieValidation(htmlInfo[1],EventList.this)){
					eventList = HtmlBrowser.jsonEventProcessor(jsonString,htmlInfo[1],EventList.this);
					SQLiteAdapter sql = new SQLiteAdapter(EventList.this);
					sql.open("W");
					try {
						JSONObject e = new JSONObject();
						for(int i = 0; i < eventList.size();i++){
							e.accumulate("event", eventList.get(i).get("title"));
						}
						List<NameValuePair> info = new ArrayList<NameValuePair>(2);
						info.add(new BasicNameValuePair("EventName", e.toString()));
						String[] jsonData = HtmlBrowser.postExecutor("http://brainfuck.nord.is:2005/", info);
						if(!jsonData[0].contains("Exception")){
							locationList = sql.updateLocation(jsonData[0], eventList);
						}	

					} catch (Exception e){
						e.printStackTrace();
					}
					sql.close();	
					return "OK";
				} else 
					return "CookieException";
			}
			return "404";
		}

		@Override
		protected void onPostExecute(String status) {
			progressBar.dismiss();
			String[] from = { "eventname", "date", "countdown" };
			int[] to = { R.id.eventname, R.id.eventdate, R.id.countdown };

			if (status.matches("OK")) {
					adapter = new EventListAdapter(EventList.this, eventList,R.layout.list_event, from, to);
					listView.setAdapter(adapter);
				
			} else if (status.contains("CookieException")) {
				HtmlBrowser.expiredCookieHandler(EventList.this);
			} else {
				Toast toast;
				if (eventList != null) {
					adapter = new EventListAdapter(EventList.this, eventList,R.layout.list_event, from, to);
					listView.setAdapter(adapter);
					String message = "Ekkert netsamband\nSýni lítið af upplýsingum";
					toast = Toast.makeText(EventList.this, message,Toast.LENGTH_SHORT);
					toast.show();
				} else {
					String message = "Ekkert netsamband. Til að sækja atburði í fyrsta sinn þarf nettengingu";
					Intent menus = new Intent(EventList.this, Menus.class);
					menus.putExtra("USERNAME", getIntent().getExtras()
							.getString("USERNAME"));
					toast = Toast.makeText(EventList.this, message,
							Toast.LENGTH_LONG);
					toast.show();
					startActivity(menus);
				}
			}
		}

	}
	
	@Override
	public void onBackPressed() {
		Intent eventlist = new Intent(EventList.this, Menus.class);
		eventlist.putExtra("USERNAME", getIntent().getExtras().getString("USERNAME"));
		startActivity(eventlist);
	}
}